# 把获取到的json城市信息存到数据库中
# 这个考验文件处理操作

import json

from App.ext import db
from App.models.common.city_model import My_City
from manage import app


def load_data():
    with open('./data/cities.json' , 'r' , encoding='utf-8') as cities_json_file:
        cities_json_str = cities_json_file.read()
        cities_json = json.loads(cities_json_str)       # 到这一步，就变成了json数据格式了

    return cities_json

def insert_cities(cities_json):
    cities = cities_json.get('returnValue')
    keys = cities.keys()
    # letter_lens = len(keys)

    db.app = app
    # db.drop_all()
    db.create_all()
    for key in keys:
        # print(key , '======' , cities.get(key))     # 到这一步是输出每一个字母（键）以及对应的字母下的城市信息（值）
        letter_city_lens = len(cities.get(key))     # 算出每个字母下有多少个城市
        for i in range(letter_city_lens):
            # print(key)
            # print(cities.get(key)[i].get('id'))
            # print(cities.get(key)[i].get('parentId'))
            # print(cities.get(key)[i].get('regionName'))
            # print(cities.get(key)[i].get('cityCode'))
            # print(cities.get(key)[i].get('pinYin'))

            # 将数据逐次插入数据库中
            temp = My_City()
            temp.c_letter = key
            temp.c_id = cities.get(key)[i].get('id')
            temp.c_parent_id = cities.get(key)[i].get('parentId')
            temp.c_regionName = cities.get(key)[i].get('regionName')
            temp.c_cityCode = cities.get(key)[i].get('cityCode')
            temp.c_pinYin = cities.get(key)[i].get('pinYin')
            # temp = My_City(c_letter = key , c_id = cities.get(key)[i].get('id'), c_parent_id = cities.get(key)[i].get('parentId') , c_regionName = cities.get(key)[i].get('regionName') , c_cityCode = cities.get(key)[i].get('cityCode') , c_pinYin = cities.get(key)[i].get('pinYin'))

            db.session.add(temp)
            db.session.commit()







if __name__ == '__main__':
    cities_json = load_data()
    insert_cities(cities_json)


